#include "StdAfx.h"
#include "Proactor.h"

#include "Completion_Handler.h"
#include "Async_Result.h"
#include "Win32_Proactor.h"


Proactor* Proactor::proactor_ = 0;


Proactor::Proactor(Proactor_Impl* _proactor_impl)
	: proactor_impl_(0),
	  proactor_event_end_loop_(false)
{
	this->proactor_impl_ = _proactor_impl;

	if(0 == this->proactor_impl_)
	{
		Win32_Proactor* implementation = new Win32_Proactor(2);
		this->proactor_impl_ = implementation;
	}
}

Proactor::~Proactor(void) 
{

}

Proactor* Proactor::instance ()
{
	if(0 == Proactor::proactor_)
	{
		if(0 == Proactor::proactor_)
		{
			proactor_ = new Proactor(0);
		}
	}

	return Proactor::proactor_;
}

bool Proactor::register_handle(HANDLE _handle, const void* completion_key)
{
	return this->proactor_impl_->register_handle(_handle, completion_key);
}

int Proactor::handle_events(const Time_Value time_value)
{
	return this->proactor_impl_->handle_events(time_value);
}

int Proactor::proactor_event_run_loop()
{
	int result = 0;
	
	for(;;)
	{
		result = this->handle_events();

		if(-1 == result)
		{
			break;
		}
	}

	proactor_event_end_loop_ = true;
	return result;
}

bool Proactor::proactor_event_end_loop() 
{ 
	return proactor_event_end_loop_; 
}
